package in.muton.edushare.grading.panels.prevgrades;

import in.muton.edushare.pages.EduShareBasePage;
import in.muton.edushare.pages.common.EdusharePanel;
import in.muton.edushare.panels.upload.Uploader;
import in.muton.edushare.panels.upload.exceptions.FileProcessingException;
import in.muton.edushare.panels.upload.exceptions.InvalidUploadFileException;
import in.muton.edushare.wicket.models.CayenneModel;

import java.io.IOException;

import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.upload.FileUpload;
import org.apache.wicket.markup.html.form.upload.FileUploadField;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.Model;

import com.edushare.common.dao.FileDirectoriesDAO;
import com.edushare.common.vo.FileDirectories;
import com.edushare.common.vo.FilesUploaded;

public abstract class GeneralFileUpload extends EdusharePanel {
	private static final long serialVersionUID = 7778249352469163737L;
	private Form<Void> form = null;
	private FileUploadField fufi;

	public GeneralFileUpload(String id, EduShareBasePage page) {
		super(id, page);
		form = new Form<Void>("uploadForm") {
			@Override
			public void onSubmit() {
				formSubmit();
			}

			private static final long serialVersionUID = 3976000346293823282L;
		};
		form.setMultiPart(true);
		fufi = new FileUploadField("fufi", new Model<FileUpload>());
		form.add(fufi);
		add(form);
	}

	public void formSubmit() {
		FileUpload fileUpload = fufi.getFileUpload();
		FileDirectories fd = new FileDirectoriesDAO(getORMInterface())
				.getOrCreateSystemTempDir(getLoggedInUser());
		Uploader uploader = new Uploader(fileUpload, fd);
		FilesUploaded uploadedFile = null;
		try {
			uploadedFile = uploader.startUploading();
		} catch (InvalidUploadFileException e) {
			warn("Invalid File.");
			e.printStackTrace();
		} catch (IOException e) {
			warn("Error during upload");
			e.printStackTrace();
		} catch (FileProcessingException e) {
			warn("Error in processing this file");
			e.printStackTrace();
		}
		getORMInterface().commitAllChanges();
		IModel<FilesUploaded> model = null;
		if(uploadedFile != null)
			model = new CayenneModel<FilesUploaded>(uploadedFile);
		processFile(model);
	}

	public abstract void processFile(IModel<FilesUploaded> fileModel);
}